package com.hzit.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import com.alibaba.fastjson.JSON;
import com.hzit.search.entity.ItemEntity;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
@RabbitListener(queues = "updateStatus")
public class SyncData {
	@Autowired
	private ElasticsearchClient client;

	//1. 接受到经过审核通过的sku商品列表
	@RabbitHandler
	public void getMessage(String data) throws IOException {
		//1.1 将其转换为集合对象
		List<ItemEntity> itemList = JSON.parseArray(data, ItemEntity.class);
		System.out.println("itemList = " + itemList);
		BulkRequest.Builder br = new BulkRequest.Builder();

		//1.2 同步到索引库
		for (ItemEntity itemEntity : itemList) {
			//1.2.1 得到规格信息
			String spec = itemEntity.getSpec();
			//1.2.2 将上面的字符串转换为map
			Map<String,Object> map = JSON.parseObject(spec, Map.class);
			//1.2.3 为当前的itemEntity赋值
			itemEntity.setSpecMap(map);
		}
		//1.3 遍历列表并添加到索引库中
		for (ItemEntity itemEntity : itemList) {
			br.operations(op->op.index(
					idx->idx.index("item")
							.id(itemEntity.getId() + "")
							.document(itemEntity)
			));
		}
		BulkResponse result = client.bulk(br.build());
	}
}
